package com.example.smartwaterapi.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Token活跃时间管理服务
 * 用于跟踪和管理用户Token的活跃状态，配合前端的30天不活跃自动过期机制
 */
@Slf4j
@Service
public class TokenActivityService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String TOKEN_ACTIVITY_PREFIX = "token:activity:";
    private static final String USER_ACTIVITY_PREFIX = "user:activity:";
    
        // 30天的毫秒数
    private static final long INACTIVITY_EXPIRE_TIME = 30 * 24 * 60 * 60 * 1000L;

    // Redis中存储的过期时间（31天，比实际检查时间多1天作为缓冲）
    private static final long REDIS_EXPIRE_TIME = 31 * 24 * 60 * 60;

    /**
     * 记录用户Token活跃时间
     */
    public void recordTokenActivity(String userId, String tokenId) {
        try {
            long currentTime = System.currentTimeMillis();
            
            // 记录Token级别的活跃时间
            String tokenKey = TOKEN_ACTIVITY_PREFIX + tokenId;
            redisTemplate.opsForValue().set(tokenKey, currentTime, REDIS_EXPIRE_TIME, TimeUnit.SECONDS);
            
            // 记录用户级别的活跃时间
            String userKey = USER_ACTIVITY_PREFIX + userId;
            redisTemplate.opsForValue().set(userKey, currentTime, REDIS_EXPIRE_TIME, TimeUnit.SECONDS);
            
            log.debug("记录用户 [{}] Token [{}] 活跃时间: {}", userId, tokenId, currentTime);
        } catch (Exception e) {
            log.error("记录Token活跃时间失败: userId={}, tokenId={}, error={}", userId, tokenId, e.getMessage());
        }
    }

    /**
     * 获取Token的最后活跃时间
     */
    public Long getTokenLastActiveTime(String tokenId) {
        try {
            String tokenKey = TOKEN_ACTIVITY_PREFIX + tokenId;
            Object activeTime = redisTemplate.opsForValue().get(tokenKey);
            
            if (activeTime instanceof Long) {
                return (Long) activeTime;
            } else if (activeTime instanceof Integer) {
                return ((Integer) activeTime).longValue();
            } else if (activeTime instanceof String) {
                return Long.parseLong((String) activeTime);
            }
            
            return null;
        } catch (Exception e) {
            log.warn("获取Token活跃时间失败: tokenId={}, error={}", tokenId, e.getMessage());
            return null;
        }
    }

    /**
     * 检查Token是否因不活跃而过期
     */
    public boolean isTokenInactivityExpired(String tokenId) {
        try {
            Long lastActiveTime = getTokenLastActiveTime(tokenId);
            
            if (lastActiveTime == null) {
                // 如果没有活跃时间记录，认为已过期
                log.debug("Token [{}] 无活跃时间记录，认为已过期", tokenId);
                return true;
            }
            
            long timeSinceLastActive = System.currentTimeMillis() - lastActiveTime;
            boolean expired = timeSinceLastActive > INACTIVITY_EXPIRE_TIME;
            
            if (expired) {
                log.debug("Token [{}] 因不活跃过期: lastActiveTime={}, timeSinceLastActive={}ms, expireTime={}ms", 
                         tokenId, lastActiveTime, timeSinceLastActive, INACTIVITY_EXPIRE_TIME);
            }
            
            return expired;
        } catch (Exception e) {
            log.error("检查Token不活跃过期失败: tokenId={}, error={}", tokenId, e.getMessage());
            return true; // 出错时认为已过期，更安全
        }
    }

    /**
     * 清除Token的活跃时间记录
     */
    public void clearTokenActivity(String tokenId) {
        try {
            String tokenKey = TOKEN_ACTIVITY_PREFIX + tokenId;
            redisTemplate.delete(tokenKey);
            log.debug("清除Token [{}] 活跃时间记录", tokenId);
        } catch (Exception e) {
            log.warn("清除Token活跃时间记录失败: tokenId={}, error={}", tokenId, e.getMessage());
        }
    }

    /**
     * 生成Token的唯一标识符（基于用户ID和时间戳）
     */
    public String generateTokenId(String userId) {
        return userId + "_" + System.currentTimeMillis();
    }
} 